﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;

namespace InterMessage
{
    public class BroadCaster
    {
        #region Private Members
        private static BroadCaster _broadCaster;
        private List<IMessageClient> _messageClientList;
        #endregion

        #region Contructor
        private BroadCaster()
        {
        }
        #endregion

        #region Properties
        public static BroadCaster GetInstance
        {
            get
            {
                if (_broadCaster == null)
                    _broadCaster = new BroadCaster();

                return _broadCaster;
            }
        }

        private List<IMessageClient> MessageClientList
        {
            get
            {
                if (this._messageClientList == null)
                    this._messageClientList = new List<IMessageClient>();

                return this._messageClientList;
            }
        }
        #endregion

        #region Private Methods
        private bool IsExist(IMessageClient msgClient)
        {
            return this.MessageClientList.IndexOf(msgClient) > 0;
        }
        #endregion

        #region Public Methods
        public void Attach(IMessageClient msgClient)
        {
            if (!this.IsExist(msgClient))
                this.MessageClientList.Add(msgClient);
        }

        public void Detach(IMessageClient msgClient)
        {
            if (this.IsExist(msgClient))
                this.MessageClientList.Remove(msgClient);
        }

        public void SendMessage(IMessageClient sender, int type, Object message)
        {
            foreach (IMessageClient msgClient in this.MessageClientList)
            {
                if (!msgClient.Equals(sender))
                    msgClient.ReceiveMessage(type, message);
            }
        }
        #endregion
    }
}
